import time
from datetime import datetime, timedelta

from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News, Category
from info.response_code import RET
from utils.common import user_login_data
from utils.image_storage import storage
from . import admin_blu


@admin_blu.route('/index')
@user_login_data
def index():
    """主页"""
    user = g.user.to_dict()
    return render_template('admin/index.html',user = user)


@admin_blu.route('/logout')
def logout():
    """退出管理员登陆"""
    session.pop('mobile', None)
    session.pop('nick_name', None)
    session.pop('user_id', None)
    session.pop('is_admin', None)
    return redirect('/')


@admin_blu.route('/user_count')
@user_login_data
def user_count():
    """用户统计"""
    user = g.user
    # 用户总数
    totle_count = 0
    try:
        totle_count = User.query.filter(User.is_admin != True).count()
    except Exception as e:
        current_app.logger.error(e)

    # 每月新增用户数
    mon_count = 0
    t = time.localtime()
    begin_mon_date = datetime.strptime('%d-%02d-01'%(t.tm_year,t.tm_mon),'%Y-%m-%d')
    try:
        mon_count = User.query.filter(User.is_admin == False,User.create_time >begin_mon_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 每日新增
    day_count = 0
    begin_day_date = datetime.strptime('%d-%02d-%02d'%(t.tm_year,t.tm_mon,t.tm_mday),'%Y-%m-%d')
    try:
        day_count = User.query.filter(User.is_admin == False,User.create_time >begin_day_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 图表数据
    active_time = []
    active_count = []
    # 今天的时间
    today_date_str = '%d-%02d-%02d'%(t.tm_year,t.tm_mon,t.tm_mday)
    # 转成时间
    today_date = datetime.strptime(today_date_str,'%Y-%m-%d')
    for i in range(0,31):
        begin_date = today_date - timedelta(days = i)
        end_date = today_date - timedelta(days = i-1)
        count = User.query.filter(User.is_admin == False, User.last_login >= begin_date ,User.last_login <= end_date).count()
        active_count.append(count)
        active_time.append(begin_date.strftime('%Y-%m-%d'))

    active_time.reverse()
    active_count.reverse()

    data = {
        'totle_count':totle_count,
        'mon_count':mon_count,
        'day_count':day_count,
        'active_time':active_time,
        'active_count':active_count
    }
    return render_template('admin/user_count.html',data = data)


@admin_blu.route('/user_list')
def user_list():
    """用户列表"""
    p = request.args.get('p',1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/user_list.html',errmsg = "页码传入错误")

    try:
        paginates = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(p, constants.ADMIN_USER_PAGE_MAX_COUNT,False)
        current_page = paginates.page
        totle_pages = paginates.pages
        user_model_list = paginates.items
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/user_list.html',errmsg = '查询数据库错误')

    user_dict_li = []
    for user in user_model_list:
        user_dict_li.append(user.to_dict())

    data ={
        'current_page':current_page,
        'total_page':totle_pages,
        'users':user_dict_li

    }
    return render_template('admin/user_list.html',data = data)


@admin_blu.route('/news_review')
def news_review():
    """新闻审核"""
    p = request.args.get('p', 1)
    keywords = request.args.get('keywords','')
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    filters = []
    if keywords:
        filters.append(News.title.contains(keywords))

    current_page=1
    total_page=1
    news_model_list=[]
    try:
        paginates = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        current_page = paginates.page
        total_page = paginates.pages
        news_model_list = paginates.items
    except Exception as e:
        current_app.logger.error(e)

    if not (current_page,total_page,news_model_list):
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_dict())

    data ={
        'current_page':current_page,
        'total_page':total_page,
        'news':news_dict_li
    }
    return render_template('admin/news_review.html',data= data)


# 请求方式：GET、POST
# 请求地址：news_review_detail
# 请求参数：news_id
@admin_blu.route('/news_review_detail',methods=['GET','POST'])
def news_review_detail():
    """新闻详情审核"""
    # GET请求
    if request.method == 'GET':
        # 获取参数
        news_id = request.args.get('news_id')

        # 校验参数
        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)

        news_model = None
        try:
            news_model = News.query.filter(News.id ==news_id).first()
        except Exception as e:
            current_app.logger.error(e)

        if not news_model:
            return '未查询到新闻详情'

        # 新闻详情
        news = news_model.to_dict()
        data ={
            'news':news
        }

        return render_template('admin/news_review_detail.html',data = data)

    # POST请求
    # 获取参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 验证参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg = '参数不齐全')

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg= '参数错误')

    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg= '参数错误')

    # 逻辑处理

    try:
        news= News.query.filter(News.id == news_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno= RET.DATAERR, errmsg= '查询数据库错误')

    if not news:
        return jsonify(errno = RET.DATAERR,errmsg='未查询到相关新闻')

    if action == 'accept':
        news.status = 1
    else:
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg= '参数错误')
        news.status = -1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg='数据库错误')

    return jsonify(errno='Ok', errmsg='操作成功')


# 请求地址：news_edit
# 请求方式:get
# 请求参数：p, keywords
# 返回：模板
@admin_blu.route('/news_edit')
def news_edit():
    # 获取参数
    p = request.args.get('p',1)
    keywords = request.args.get('keywords','')

    # 校验参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return '参数错误'

    # 逻辑处理
    paginates = None
    current_page = 1
    total_page = 1
    news_model_list =[]
    try:
        paginates = News.query.filter(News.title.contains(keywords)).paginate(p,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        current_page = paginates.page
        total_page = paginates.pages
        news_model_list = paginates.items
    except Exception as e:
        current_app.logger.error(e)

    if not paginates:
        return '未查询到数据'

    news_list = []
    for news in news_model_list:
        news_list.append(news.to_dict())

    data = {
        'current_page':current_page,
        'total_page':total_page,
        'news_list':news_list
    }

    # 返回数据
    return render_template('admin/news_edit.html', data = data)


# 请求方式：GET和post(form发送参数）
# 请求地址：/news_edit_detail?news_id =
@admin_blu.route('/news_edit_detail',methods=['GET','POST'])
def news_edit_detail():

    # GET请求
    if request.method =='GET':
        news_id = request.args.get('news_id')
        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news_id:
            return '参数错误'

        try:
            news = News.query.filter(News.id == news_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return

        try:
            categories= Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return

        category_list=[]
        for category in categories:
            category_list.append(category.to_dict())

        data = {
            'news':news.to_dict(),
            'categories':category_list
        }
        return render_template('admin/news_edit_detail.html',data = data)

    # POST请求
    if request.method =='POST':
        # 获取参数(title,digest,content,index_image,category_id)
        news_id =request.form.get('news_id')
        title = request.form.get('title')
        content = request.form.get('content')
        digest = request.form.get('digest')
        index_image = request.form.get('index_image')
        category_id = request.form.get('category_id')

        # 校验参数
        if not all([news_id,title,content,digest,category_id]):
            current_app.logger.error(e)
            return jsonify(errno = RET.PARAMERR, errmsg='参数不全')

        try:
            category_id = int(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.PARAMERR, errmsg = '参数错误')

        try:
            news = News.query.filter(News.id == news_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.DBERR, errmsg = '查询数据库失败')

        if index_image:
            try:
                index_image = index_image.read()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno= RET.IOERR, errmsg = '文件读写错误')

            try:
                key = storage(index_image)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno= RET.THIRDERR, errmsg='第三方错误')
            news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

        if not news:
            return jsonify(errno=RET.DBERR, errmsg ='要编辑的新闻不存在')
        news.title = title
        news.digest = digest
        news.category_id = category_id
        news.content = content

        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno = RET.DBERR, errmsg='数据提交错误')

        return jsonify(errno = RET.OK ,errmsg = '编辑成功')


# 请求地址：news_edit
# 请求方式：GET、POST
# 参数：category_id,name
@admin_blu.route('/news_type',methods=['GET', 'POST'])
def news_type():
    # GET请求
    if request.method == 'GET':
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_type.html',errmsg ='查询数据库错误')

        if not categories:
            return render_template('admin/news_type.html', errmsg='未查询到任何分类')

        category_list=[]
        for category in categories:
            category_list.append(category.to_dict())

        data ={
            'categories':category_list
        }

        # 返回数据
        return render_template('admin/news_type.html', data = data)

    # POST请求
    # 获取参数
    category_id = request.json.get('id')
    category_name = request.json.get('name')

    # 校验参数
    if not category_name:
        return jsonify(errno = RET.PARAMERR, errmsg = '参数错误')

    if category_id:
        try:
            category = Category.query.filter(Category.id== category_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.DBERR, errmsg='查询数据库错误')

        if not category:
            return jsonify(errno=RET.DBERR, errmsg='查询数据库错误')

        category.name=category_name

    else:
        category = Category()
        category.name = category_name

    try:
        db.session.add(category)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据提交错误')

    return jsonify(errno=RET.OK, errmsg = '分类保存成功')










